package com.wlps.service.impl;

import com.wlps.contant.Contant;
import com.wlps.entity.SysRole;
import com.wlps.entity.SysUser;
import com.wlps.mapper.SysRoleMapper;
import com.wlps.result.ResultPageVo;
import com.wlps.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlps.vo.RoleParm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 角色表(sys_role) 服务实现类
 * </p>
 *
 * @author ZWYZY
 * @since 2020-07-30
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService, InitializingBean {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 初始化缓存
     */
    void initSysRole() {
        if (!redisTemplate.hasKey(Contant.ROLES_KEY)) {
            List<SysRole> sysRoleList = baseMapper.selectList(null);
            redisTemplate.opsForValue().set(Contant.ROLES_KEY, sysRoleList);
            log.info("初始化所有角色-------存入缓存数据");
        }
    }

    @Override
    public ResultPageVo<List<SysRole>> selectRole(RoleParm roleParm) {
        initSysRole();

        //总条数
        int count;
        //偏移量
        int fromNum;
        //终止量
        int toNum;
        List<SysRole> sysRoleList = (List<SysRole>) redisTemplate.opsForValue().get(Contant.ROLES_KEY);


        if (StringUtils.isBlank(roleParm.getName())) {
            //不是条件查询，redis
            count = sysRoleList.size();

        } else {
            Stream<SysRole> stream = sysRoleList.stream();
            if (!StringUtils.isBlank(roleParm.getName())) {
                String name = roleParm.getName();
                stream = stream.filter(x -> x != null && name.equals(x.getName()));
            }

            sysRoleList = stream.collect(Collectors.toList());
            count = sysRoleList.size();
        }
        //当前页从第几条开始查
        fromNum = roleParm.getPageSize() * (roleParm.getCurrentPage() - 1);
        if (fromNum >= count) {
//            sysUserList=null;
        } else {
            //当前页最后第几条
            toNum = fromNum + roleParm.getPageSize() >= count ? count : fromNum + roleParm.getPageSize();
            sysRoleList = sysRoleList.subList(fromNum, toNum);
        }
        //分页返回值封装
        ResultPageVo resultPageVo = new ResultPageVo("响应成功", 200, (long) roleParm.getPageSize(), (long) roleParm.getCurrentPage(), (long) count, sysRoleList);


        return resultPageVo;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initSysRole();
    }
}
